package com.example.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

@Slf4j
public class TcpMessageDecoder extends ByteToMessageDecoder {
    
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        // 检查是否是MQTT消息
        if (in.readableBytes() >= 1) {
            in.markReaderIndex();
            byte firstByte = in.readByte();
            in.resetReaderIndex();
            
            if ((firstByte & 0xF0) == 0x10 || // CONNECT
                (firstByte & 0xF0) == 0x30 || // PUBLISH
                (firstByte & 0xF0) == 0x80 || // SUBSCRIBE
                (firstByte & 0xF0) == 0xC0 || // PINGREQ
                (firstByte & 0xF0) == 0xE0) { // DISCONNECT
                // 是MQTT消息，传递给下一个处理器
                out.add(in.retain());
            } else {
                // 是TCP消息，直接处理
                byte[] data = new byte[in.readableBytes()];
                in.readBytes(data);
                log.info("Received TCP message from {}: {}", 
                    ctx.channel().remoteAddress(), 
                    new String(data));
                
                // 回复TCP消息
                ctx.writeAndFlush(ctx.alloc().buffer()
                    .writeBytes("TCP message received\n".getBytes()));
            }
        }
    }
} 